package com.example.city_defense;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Color;
import android.graphics.Paint;

import com.badlogic.androidgames.framework.Game;
import com.badlogic.androidgames.framework.Graphics;
import com.badlogic.androidgames.framework.Graphics.PixmapFormat;
import com.badlogic.androidgames.framework.Input.TouchEvent;
import com.badlogic.androidgames.framework.Screen;
import com.example.city_defense.sprites.*;
import com.example.city_defense.sprites.Bullet.State;
import com.example.city_defense.sprites.Vehicle.VehicleState;

public class GameScreen extends Screen {

	enum GameState {
		Running, Paused, GameOver
	}

	enum GameActivity {
		Sell, Build, NoAction
	};

	enum BarState {
		Basic, Advanced, Abilities, Buildings
	};

	GameState state = GameState.Running;
	GameActivity activity = GameActivity.NoAction;
	BarState barState = BarState.Basic;

	public ArrayList<Tower> listTower;
	public ArrayList<Vehicle> listVehicle;
	public ArrayList<Bullet> listBullet;

	CountTime time;
	World world;
	Paint paint = new Paint();
	float deltatime;
	private int level;
	private int map;
	private int money = 350;
	private int item = 0;
	private int people = 10;
	private int currentAttack = 0;

	public GameScreen(Game game, int level, int map) {
		super(game);
		// TODO Auto-generated constructor stub
		paint.setColor(Color.YELLOW);
		paint.setTextSize(50);
		this.map = map;
		this.level = level;
		this.listTower = new ArrayList<Tower>();
		this.listVehicle = new ArrayList<Vehicle>();
		this.listBullet = new ArrayList<Bullet>();
		this.loadingMap();
		time = new CountTime(this);
	}

	private void loadingMap() {
		world = new World(this.map, this.level);
		String name = "map" + map + ".png";
		Asset.map = game.getGraphics().newPixmap(name, PixmapFormat.ARGB4444);

	}

	@Override
	public void update(float deltaTime) {
		// TODO Auto-generated method stub
//		List<KeyEvent> keyEvents = game.getInput().getKeyEvents();
//		int sizeKeyEvent = keyEvents.size();
//		for(int i =0 ; i< sizeKeyEvent ; i++){
//			KeyEvent keyEvent = keyEvents.get(i);
//			if(keyEvent.type== KeyEvent.KEY_DOWN /*&& key code*/ ){
//				
//			}
//		}
		List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
		this.deltatime = deltaTime;
		if (state == GameState.Running) {
			updateRunning(touchEvents);
		}
		if (state == GameState.Paused) {
			updatePause(touchEvents);
		}
		if (state == GameState.GameOver) {
			updateGameOver(touchEvents);
		}

	}

	public void updateRunning(List<TouchEvent> touchEvents) {

		// update time ===================================================
		time.update(this.deltatime);

		// update Tower ==================================================
		// Log.i("List Tower", listTower.size()+"");
		for (Tower tower : listTower) {
			tower.update(this.deltatime);
		}

		// Log.i("List Bullet", listBullet.size()+"");
		// update bullet =================================================
		for (int bullet = 0; bullet < listBullet.size(); bullet++) {
			Bullet bulleti = listBullet.get(bullet);
			bulleti.update(deltatime);
			if (bulleti.state == State.OutScreen
					|| bulleti.state == State.Finish) {
				listBullet.remove(bullet);
				bullet--;
			}
		}

		// Log.i("List Vehicle", listVehicle.size()+"");
		// update vehicle ===============================================
		for (int vehicle = 0; vehicle < listVehicle.size(); vehicle++) {
			Vehicle vehiclei = listVehicle.get(vehicle);

			if (vehiclei.state == VehicleState.Finish) {
				this.listVehicle.remove(vehicle);
				people--;
				if (Setting.soundEnable) {
					Asset.lose.play(1);
				}
				vehicle--;
			} else if (vehiclei.state == VehicleState.Explode) {
				this.money += vehiclei.money;
				this.listVehicle.remove(vehicle);
				vehicle--;
				if (Setting.soundEnable) {
					Asset.explosion.play(1);
				}
			} else {
				vehiclei.move(deltatime);

			}
		}
		// Update activity Game ===========================================
		int len = touchEvents.size();
		for (int i = 0; i < len; i++) {
			TouchEvent touchEvent = touchEvents.get(i);
			// Check Exit
			if (inBounds(touchEvent, 750, 1250, 50, 50)
					&& touchEvent.type == TouchEvent.TOUCH_DOWN) {
				System.exit(0);
			}
			// Only check Touch Down
			if (touchEvent.type == TouchEvent.TOUCH_DOWN) {

				// Touch Bar and Items Menu
				if (touchEvent.y >= 1030) {
					// Basic Bar
					if (inBounds(touchEvent, 0, 1030, 160, 50)) {
						this.barState = BarState.Basic;
						this.activity = GameActivity.NoAction;
						this.item = 0;

					}
					// Advanced Bar
					else if (inBounds(touchEvent, 160, 1030, 160, 50)) {
						this.barState = BarState.Advanced;
						this.activity = GameActivity.NoAction;
						this.item = 0;
					}
					// Abilities Bar
					else if (inBounds(touchEvent, 320, 1030, 160, 50)) {
						this.barState = BarState.Abilities;
						this.activity = GameActivity.NoAction;
						this.item = 0;
					}
					// Buildings Bar
					else if (inBounds(touchEvent, 480, 1030, 160, 50)) {
						this.barState = BarState.Buildings;
						this.activity = GameActivity.NoAction;
						this.item = 0;
					}
					// Select Item
					else if (touchEvent.y >= 1081) {

						activity = GameActivity.Build;
						item = (int) touchEvent.x / 160 + 1;
					}
					if (Setting.soundEnable) {
						Asset.click.play(1);
					}
				}// End Touch Bar and Touch menu item

				// Touch in control Area
				else if (touchEvent.y >= 875) {
					// Touch Play Button
					if (touchEvent.x < 160) {
						if (Setting.soundEnable) {
							Asset.click.play(1);
						}
						if (listVehicle.size() == 0) {

						}
						this.time.skip();
					}
					// Touch Sell Button
					else if (touchEvent.x < 320) {
						this.activity = GameActivity.Sell;
						if (Setting.soundEnable) {
							Asset.click.play(1);
						}
					}
					// Touch Pause Button
					else if (inBounds(touchEvent, 320, 945, 80, 85)) {
						this.state = GameState.Paused;
					}
					// Touch Music Button
					else if (inBounds(touchEvent, 400, 945, 80, 85)) {
						Setting.soundEnable = !Setting.soundEnable;
						if (Setting.soundEnable) {
							Asset.main.play();
						} else
							Asset.main.stop();
					}
				}

				// Touch Map Area
				else if (touchEvent.y >= 75) {
					// Touch Map when Build
					if (activity == GameActivity.Build && item != 0) {
						int ax = touchEvent.x / 50;
						int ay = (touchEvent.y - 75) / 50;
						if (world.canBuildTower(ax, ay)) {
							int xCoor = 50 * ax + 25;
							int yCoor = 50 * ay + 100;
							int t = item
									+ 5
									* (barState == BarState.Basic ? 0
											: (barState == BarState.Advanced ? 1
													: 2));
							this.listTower.add(new Tower(this, xCoor, yCoor, t,
									world.tileMap[ay][ax]));
							world.tileMap[ay][ax] = 5;
							if (Setting.soundEnable) {
								Asset.click.play(1);
							}

						} else {
							this.activity = GameActivity.NoAction;
							if (Setting.soundEnable) {
								Asset.error.play(1);
							}
						}
					}
					// Touch Map when Sell
					else if (activity == GameActivity.Sell) {
						activity = GameActivity.NoAction;
						int ax = touchEvent.x / 50;
						int ay = (touchEvent.y - 75) / 50;
						int x = 50 * ax + 25;
						int y = 50 * ay + 100;
						int size = this.listTower.size();
						boolean success = false;
						for (int tower = 0; tower < size; tower++) {
							if (listTower.get(tower).x == x
									&& listTower.get(tower).y == y) {
								world.tileMap[ay][ax] = listTower.get(tower).base;
								listTower.remove(tower);
								activity = GameActivity.Sell;
								success = true;
								break;
							}
						}
						if (success) {
							if (Setting.soundEnable)
								Asset.click.play(1);
						} else {
							if (Setting.soundEnable)
								Asset.error.play(1);
							activity = GameActivity.NoAction;
						}
					}
				}
			}
		}
	}

	public void updatePause(List<TouchEvent> touchEvents) {
		int len = touchEvents.size();
		for (int i = 0; i < len; i++) {
			TouchEvent touchEvent = touchEvents.get(i);
			if(touchEvent.type==TouchEvent.TOUCH_DOWN){
				if(inBounds(touchEvent, 202, 490, 348, 358)){
					this.state = GameState.Running;
				}
				
			}
		}
	}

	public void updateGameOver(List<TouchEvent> touchEvents) {

	}

	@Override
	public void present(float deltaTime) {
		// TODO Auto-generated method stub

		// drawWorld(world);
		if (state == GameState.Running) {
			drawRunningUI();
		}
		if (state == GameState.Paused) {
			drawPauseUI();
		}
		if (state == GameState.GameOver) {
			drawGameOverUI();
		}
	}

	public void drawWorld(World world2) {
		// TODO Auto-generated method stub
		Graphics g = game.getGraphics();

	}

	public void drawRunningUI() {
		// TODO Auto-generated method stub

		Graphics g = game.getGraphics();
		// Draw Map=================================================================
		g.drawPixmap(Asset.map, 0, 75, 0, 0, 801, 1281);
		// Draw Vehicle=============================================================
		for (Vehicle vehicle : listVehicle) {
			g.drawVehicle(vehicle.image, vehicle.x, vehicle.y, vehicle.matrix);
			g.drawRect(vehicle.x - vehicle.totalBlood / 2, vehicle.y
					- vehicle.image.getHeight() / 2 - 12, vehicle.totalBlood,
					8, Color.BLACK);
			g.drawRect(vehicle.x - vehicle.totalBlood / 2, vehicle.y
					- vehicle.image.getHeight() / 2 - 12, vehicle.currentBlood,
					8, Color.GREEN);
		}

		// Draw Tower===============================================================

		for (Tower tower : listTower) {
			g.drawPixmap(tower.image, tower.x - tower.image.getWidth() / 2,
					tower.y - tower.image.getHeight() / 2);
		}
		if (listBullet.size() != 0) {
			for (Bullet bullet : listBullet) {
				g.drawPixmap(bullet.image, bullet.x - bullet.image.getWidth()
						/ 2, bullet.y - bullet.image.getHeight() / 2);
			}
		}

		// Draw Information of Player================================================

		// Draw Control
		if (Setting.soundEnable) {
			g.drawPixmap(Asset.control, 0, 875, 0, 0, 799, 155);
		} else {
			g.drawPixmap(Asset.control, 0, 875, 0, 155, 800, 310);
		}
		g.drawText(time.getTime(), 350, 922, paint);

		// Draw Top
		g.drawPixmap(Asset.top, 0, 0);
		g.drawPixmap(Asset.coin, 10, 10);
		g.drawPixmap(Asset.people, 610, 10);
		g.drawText(" : " + this.money, 65, 55, paint);
		g.drawText(" : " + this.people, 690, 55, paint);

		// Draw Bar and Item
		if (this.barState == BarState.Basic) {
			g.drawPixmap(Asset.bar, 0, 1030, 0, 0, 800, 250);
		} else if (this.barState == BarState.Advanced) {
			g.drawPixmap(Asset.bar, 0, 1030, 0, 250, 800, 250);
		} else if (this.barState == BarState.Abilities) {
			g.drawPixmap(Asset.bar, 0, 1030, 0, 500, 800, 250);
		} else if (this.barState == BarState.Buildings) {
			g.drawPixmap(Asset.bar, 0, 1030, 0, 750, 800, 250);
		}
		// Fill Item is Selected
		if (this.activity == GameActivity.Build) {
			g.drawPixmap(Asset.chosen, (item - 1) * 160, 1080);
			g.drawPixmap(Asset.grid, 0, 75);
		} else if (activity == GameActivity.Sell) {
			g.drawPixmap(Asset.chosen, 160, 875, 0, 0, 160, 155);
		}

	}

	public void drawPauseUI() {
		// TODO Auto-generated method stub
		Graphics g = game.getGraphics();
		this.drawRunningUI();
		g.drawPixmap(Asset.pause_background, 0, 0);

	}

	public void drawGameOverUI() {
		// TODO Auto-generated method stub
		Graphics g = game.getGraphics();

	}

	@Override
	public void pause() {

	}

	@Override
	public void resume() {
		// TODO Auto-generated method stub

	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub
	}

	public boolean inBounds(TouchEvent event, int x, int y, int width,
			int height) {
		// TODO Auto-generated method stub
		if (event.x > x && event.x < x + width - 1 && event.y > y
				&& event.y < y + height - 1)
			return true;
		else
			return false;
	}

	public void startAttack() {
		int t = world.scenario.get(currentAttack).getNumber();
		for (int i = 0; i < t; i++) {
			listVehicle.add(new Vehicle(this, this.world, world.scenario.get(
					currentAttack).getType(), world.startPosition[i][5],
					world.startPosition[i][4], world.startPosition[i][1],
					world.startPosition[i][0], world.startPosition[i][3],
					world.startPosition[i][2], world.scenario
							.get(currentAttack).getFaster(), world.scenario
							.get(currentAttack).getRecovery()));
		}
		currentAttack++;
	}
}